﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using WMEncoderLib;
using System.Net.Mail;
//using WMPREVIEWLib;


namespace BugSnapper
{
    public partial class ucBugRecorder : UserControl
    {
        public Logger Logger { get; set; }
        WMEncoder Encoder = null;
        public ucBugRecorder()
        {
            InitializeComponent();
            this.Logger = new Logger();
            this.Load += new EventHandler(ucBugRecorder_Load);
        }

        void ucBugRecorder_Load(object sender, EventArgs e)
        {
            try
            {
                this.Encoder = new WMEncoder();
                this.GetRecordingProfiles();
                if (this.cmbCaptureArea.Items.Contains("Full Screen"))
                {
                    this.cmbCaptureArea.SelectedItem = "Full Screen";
                }
                else
                {
                    this.cmbCaptureArea.SelectedIndex = 0;
                }
                this.groupBox1.Location = new Point(((Screen.PrimaryScreen.Bounds.Width - this.groupBox1.Width) / 2), ((Screen.PrimaryScreen.Bounds.Height - this.groupBox1.Height) / 2));
                this.txtOutPutDirectory.Text = AppGlobal.VideoRootFolderPath;
                this.txtVideoRating.Text = AppGlobal.VideoRating;
                this.txtVideoDescription.Text = AppGlobal.VideoDescription;
                this.txtVideoCopyRight.Text = AppGlobal.VideoCopyright;
                this.txtVideoTitle.Text = AppGlobal.VideoTitle;
                this.txtVideoAuthor.Text = AppGlobal.VideoAuthor;
                this.txtAuthorEmail.Text = AppGlobal.VideoAuthorEmail;
                this.txtAuthorWebsite.Text = AppGlobal.VideoAuthorWebsiteURL;
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }
        public void GetRecordingProfiles()
        {
            try
            {
                foreach (IWMEncProfile item in Encoder.ProfileCollection)
                {
                    this.cmbRecordingProfiles.Items.Add(item.Name);
                }
                if (this.cmbRecordingProfiles.Items.Contains("Screen Video/Audio High (CBR)"))
                {
                    this.cmbRecordingProfiles.SelectedItem = "Screen Video/Audio High (CBR)";
                }
                else
                {
                    this.cmbRecordingProfiles.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }
        public bool IsEmailValid(string emailaddress)
        {
            try
            {
                MailAddress m = new MailAddress(emailaddress);
                return true;
            }
            catch (FormatException ex)
            {
                this.Logger.ProcessError(ex);
                return false;
            }
        }
        public void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(this.txtAuthorEmail.Text) && !this.IsEmailValid(this.txtAuthorEmail.Text))
                {
                    this.errorProvider1.SetError(txtAuthorEmail, "Invalid Email");
                    return;
                }
                else
                {
                    this.errorProvider1.SetError(txtAuthorEmail, "");
                }
                IWMEncSourceGroup2 SrcGrp;
                IWMEncSourceGroupCollection SrcGrpColl;
                SrcGrpColl = Encoder.SourceGroupCollection;
                SrcGrp = (IWMEncSourceGroup2)SrcGrpColl.Add("SG_1");
                IWMEncVideoSource2 SrcVid;
                IWMEncAudioSource SrcAud;
                SrcVid = (IWMEncVideoSource2)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
                SrcAud = (IWMEncAudioSource)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
                SrcVid.SetInput("ScreenCapture1", "ScreenCap", "");
                SrcAud.SetInput("Default_Audio_Device", "Device", "");
                //SrcVid.Height = !string.IsNullOrEmpty(txtHeight.Text) && Convert.ToInt32(this.txtHeight.Text) > 0 ? Convert.ToInt32(this.txtHeight.Text) : Screen.PrimaryScreen.Bounds.Height;
                //SrcVid.Width = !string.IsNullOrEmpty(txtWidth.Text) && Convert.ToInt32(this.txtWidth.Text) > 0 ? Convert.ToInt32(this.txtWidth.Text) : Screen.PrimaryScreen.Bounds.Width;
                IWMEncProfileCollection ProColl;
                IWMEncProfile Pro;
                int i;
                long lLength;
                ProColl = Encoder.ProfileCollection;
                lLength = ProColl.Count;
                //for (i = 0; i < lLength - 1; i++)
                //    Console.WriteLine(ProColl.Item(i).Name);

                string profileName = !string.IsNullOrEmpty(Convert.ToString(this.cmbRecordingProfiles.SelectedItem)) ? Convert.ToString(this.cmbRecordingProfiles.SelectedItem) : "Screen Video/Audio High (CBR)";
                for (i = 0; i <= lLength - 1; i++)
                {
                    Pro = ProColl.Item(i);
                    if (Pro.Name == profileName)
                    {
                        SrcGrp.set_Profile((IWMEncProfile)Pro);
                        break;
                    }
                }
                IWMEncDisplayInfo Descr;
                try
                {
                    Descr = Encoder.DisplayInfo;
                    Descr.Author = this.txtVideoAuthor.Text;
                    Descr.Copyright = this.txtVideoCopyRight.Text;
                    Descr.Description = this.txtVideoDescription.Text;
                    Descr.Rating = this.txtVideoRating.Text;
                    Descr.Title = this.txtVideoTitle.Text;
                    IWMEncAttributes Attr;
                    Attr = Encoder.Attributes;
                    Attr.Add("URL", this.txtAuthorWebsite.Text);
                    Attr.Add("Email", this.txtAuthorEmail.Text);
                }
                catch
                {
                }
                IWMEncFile File;
                File = Encoder.File;
                if (!string.IsNullOrEmpty(this.txtOutPutDirectory.Text))
                {
                    if (!Directory.Exists(this.txtOutPutDirectory.Text))
                    {
                        Directory.CreateDirectory(this.txtOutPutDirectory.Text);
                    }
                }
                else
                {
                    MessageBox.Show("Please select the directory to save the video files and then try again.");
                    return;
                }
                File.LocalFileName = Path.Combine(this.txtOutPutDirectory.Text, "Vid" + "Img" + DateTime.Now.ToString().Replace("/", "").Replace(" ", "").Replace(":", "").Replace(".", "").Replace("_", "") + ".wmv");
                SrcVid.CroppingBottomMargin = 2;
                SrcVid.CroppingTopMargin = 2;
                SrcVid.CroppingLeftMargin = 2;
                SrcVid.CroppingRightMargin = 2;
                Encoder.Start();
                if (this.ParentForm != null)
                {
                    ((MainForm)this.ParentForm).SetMainFormWindowState(FormWindowState.Minimized);
                }
                this.SetDefaultControlsState(true, false);
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        private void btnBrowse_MouseHover(object sender, EventArgs e)
        {
            try
            {
                this.toolTip1.SetToolTip(this.btnBrowse, "Browse");
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        private void btnStart_MouseHover(object sender, EventArgs e)
        {

            try
            {
                this.toolTip1.SetToolTip(this.btnStart, "Start");
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        public void btnPause_MouseHover(object sender, EventArgs e)
        {

            try
            {
                if (string.IsNullOrEmpty(Convert.ToString(this.btnPause.Tag)) || Convert.ToString(this.btnPause.Tag) == "pause")
                {
                    this.toolTip1.SetToolTip(this.btnPause, "Pause");
                }
                else
                {
                    this.toolTip1.SetToolTip(this.btnPause, "Resume");
                }
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        public void btnPause_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(Convert.ToString(this.btnPause.Tag)) || Convert.ToString(this.btnPause.Tag) == "pause")
                {
                    this.Encoder.Pause();
                    this.SetDefaultControlsState(true, true);
                }
                else
                {
                    this.Encoder.Start();
                    this.SetDefaultControlsState(true, false);
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void btnStop_MouseHover(object sender, EventArgs e)
        {
            try
            {
                this.toolTip1.SetToolTip(this.btnStop, "Stop");
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        public void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.Encoder != null && (this.Encoder.RunState != WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPING || this.Encoder.RunState != WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED))
                {
                    this.Encoder.Stop();
                    this.SetDefaultControlsState(false, false);
                }
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        public void SetDefaultControlsState(bool isRecording, bool isPaused)
        {
            try
            {
                if (this.ParentForm != null)
                {
                    ((MainForm)this.ParentForm).RecordingState(isRecording, isPaused);
                }
                //Paused
                if (isRecording && isPaused)
                {
                    this.btnPause.Tag = "resume";
                    this.btnPause.Image = ((Image)(new ImageConverter()).ConvertFrom(Properties.Resources.Pause_Normal_Red));
                    this.btnStart.Enabled = false;
                    this.btnStop.Enabled = true;
                    this.btnPause.Enabled = true;
                }
                //Resumed
                if (isRecording && !isPaused)
                {
                    this.btnPause.Tag = "pause";
                    System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ucBugSnapper));
                    this.btnPause.Image = ((System.Drawing.Image)(resources.GetObject("btnPause.Image")));
                    this.btnStart.Enabled = false;
                    this.btnStop.Enabled = true;
                    this.btnPause.Enabled = true;
                }
                //Stopped
                if (!isRecording && !isPaused)
                {
                    this.btnPause.Tag = "pause";
                    System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ucBugSnapper));
                    this.btnPause.Image = ((System.Drawing.Image)(resources.GetObject("btnPause.Image")));
                    this.btnStart.Enabled = true;
                    this.btnStop.Enabled = false;
                    this.btnPause.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }
        public void PerformClosingActivities()
        {
            try
            {
                this.btnStop_Click(this, new EventArgs());
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        private void cmbCaptureArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (Convert.ToString(this.cmbCaptureArea.SelectedItem) == "Custom")
                {
                    this.lblHeight.Visible = true;
                    this.lblWidth.Visible = true;
                    this.txtWidth.Visible = true;
                    this.txtHeight.Visible = true;
                    if (string.IsNullOrEmpty(this.txtHeight.Text))
                    {
                        this.txtHeight.Text = Screen.PrimaryScreen.Bounds.Height.ToString();
                    }
                    if (string.IsNullOrEmpty(this.txtWidth.Text))
                    {
                        this.txtWidth.Text = Screen.PrimaryScreen.Bounds.Width.ToString();
                    }
                }
                else if (Convert.ToString(this.cmbCaptureArea.SelectedItem) == "Full Screen" || string.IsNullOrEmpty(Convert.ToString(this.cmbCaptureArea.SelectedItem)))
                {
                    this.lblHeight.Visible = false;
                    this.lblWidth.Visible = false;
                    this.txtWidth.Visible = false;
                    this.txtHeight.Visible = false;
                    this.txtHeight.Text = Screen.PrimaryScreen.Bounds.Height.ToString();
                    this.txtWidth.Text = Screen.PrimaryScreen.Bounds.Width.ToString();
                }
                else
                {
                    string[] tempArray = Convert.ToString(this.cmbCaptureArea.SelectedItem).Split('*');
                    if (tempArray.Length > 0)
                    {
                        this.txtWidth.Text = Convert.ToString(tempArray[0]).Replace(" ", "").Replace("*", "");
                    }
                    if (tempArray.Length > 1)
                    {
                        this.txtHeight.Text = Convert.ToString(tempArray[1]).Replace(" ", "").Replace("*", "");
                    }
                    this.lblHeight.Visible = false;
                    this.lblWidth.Visible = false;
                    this.txtWidth.Visible = false;
                    this.txtHeight.Visible = false;
                }
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        private void txtWidth_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        private void txtWidth_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.txtWidth.Text) && this.txtWidth.Text.Length < 1)
                {
                    this.txtWidth.Text = "0";
                }
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }

        private void txtHeight_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.txtHeight.Text) && this.txtHeight.Text.Length < 1)
                {
                    this.txtHeight.Text = "0";
                }
            }
            catch (Exception ex)
            {
                this.Logger.ProcessError(ex);
            }
        }
    }
}
